package com.wjx.article_sys.controller;

import com.wjx.article_sys.entity.Admin;
import com.wjx.article_sys.service.impl.AdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.UUID;

@Controller
public class RegisterController {
    @Autowired
    private AdminServiceImpl adminService;
    @Autowired
    private HttpServletResponse response;

    @GetMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

    @PostMapping("/register")
    public void register(String username, String password, String sex
            , String email, String tel, MultipartFile photo, String info) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        Admin adminTest = adminService.queryByUsername(username);
        if (adminTest != null) {
            response.getWriter().write("<script>alert('该用户名已存在，请从重新注册');" +
                    "window.location.href='/toRegister'" + "</script>");
        } else {
            String originalFilename = photo.getOriginalFilename();
            String fileName = UUID.randomUUID() + "_" + originalFilename;
            String dirPath = "D:\\study\\3\\一\\高级架构技术\\期末大作业\\article_manage_sys\\src\\main\\resources\\static\\images\\";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                photo.transferTo(new File(dirPath + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                response.setContentType("text/html;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("<script>alert('照片上传失败！');" +
                        "window.location.href='/toRegister';</script>");
            }
            Admin admin = new Admin(username, password, sex, email, tel, fileName, info);
            adminService.register(admin);
        }
    }

}